//定义依赖和插件
var gulp = require('gulp'),    //gulp住插件，必须配置
    uglify = require('gulp-uglify'),   //压缩js插件
    concat = require('gulp-concat'),   //合并文件，比如css、js
    rename = require('gulp-rename'),   //重新命名，比如压缩过后的文件.min.js
    connect = require('gulp-connect'), //启动一个服务器 
    open = require('gulp-open'),
    less = require('gulp-less'),  //启动gulp时自动打开一个页面
    livereload = require('gulp-livereload'),  //当保存时，页面可以自动刷新
    minifycss = require('gulp-minify-css'),
    notify = require('gulp-notify'),   //处理报错
    plumber = require('gulp-plumber'),  //发生错误时，不会阻止gulp进程；比如less编译时的语法错误
    cssmin = require('gulp-clean-css'); //css压缩，还有同样的gulp-minify-css
    
//定义html任务,需要在open中打开的
gulp.task('html', function () {
  livereload.listen();
    gulp.src('index.html')
    .pipe(connect.reload());
});
//定义less编译任务，并压缩至指定文件夹
gulp.task('css',function(){
return gulp.src('./style/*.less')
  .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')}))
  .pipe(less())
  .pipe(concat('main.css'))
  .pipe(gulp.dest('src'))  
});
//定义压缩css文件
gulp.task('cssmin',function(){
 return  gulp.src('src/*.css')
 .pipe(rename({suffix: '.min'}))
   .pipe(gulp.dest('src/min'))
   .pipe(cssmin())   
});
//合并压缩重命名js文件
// gulp.task('concatjs', function (){
// gulp.src(['grunp/**/*.js'])
// .on('error')
// .pipe(concat('controller.js'))
// .pipe(gulp.dest('controller'))
// .pipe(uglify())
// .pipe(rename({suffix: '.min'}))
// .pipe(gulp.dest('src'))
// ;
// });
//定义livereload任务，建立一个服务器
gulp.task('connect', function () {
    connect.server({
        root:__dirname,
        port:8800,        
        livereload: true
    });
});
gulp.task('openit', function() {
    var options = {
        uri: 'http://localhost:8800',
    };
    gulp.src('index.html')
        .pipe(open(options));
});

gulp.task('watch', function () {
  livereload.listen();
  var watcher = gulp.watch(['index.html','./style/*.less','src/*.css',], ['html','css','cssmin',]);
  watcher.on('change', function(file) {
  console.log('html File ' + file.path + ' was ' + file.type + ', running tasks...');
  livereload.changed(file.path)
  });
  var watcherJs = gulp.watch(['group/**/*.js','group/**/*.html'],['html']);
  watcherJs.on('change', function(file) {
  console.log('File ' + file.path + ' was ' + file.type + ', running tasks...');
  livereload.changed(file.path)
  });
});

//定义默认任务
gulp.task('default', ['html', 'connect','openit','watch','css','cssmin']);
